import {useState} from "react";
import {Image, View} from "@tarojs/components";
import Taro, {useDidShow, useLoad} from '@tarojs/taro'
import './index.scss'
import MapPin from "../../components/svg/map-pin2.svg";
import Users from "../../components/svg/users.svg";
import Calendar from "../../components/svg/calendar.svg";
import {getRequest} from "../../util/request";
import categoryMap from "../../util/categoryMapping";

export default function Index() {

  const [trainList, setTrainList] = useState<any>([]);

  useLoad(() => {
    console.log('我参与的训练页面加载')
    queryList()
  })

  useDidShow(() => {
    queryList()
  })

  const queryList = () => {
    getRequest('/bsTrain/mine',  res=> {
      setTrainList(res.data.map(item => {
        return {
          id: item.id,
          title: item.title,
          location: item.place,
          startDate: item.startDate,
          endDate: item.endDate,
          views: item.views,
          category: item.category,
          categoryName: categoryMap[item.category],
          participants: item.participants,
          image: item.cover,
          status: item.status,
        }
      }))
    })
  }

  const gotoPage = (id) => {
    Taro.navigateTo({url: `/pages/traindetail/index?trainId=${id}`});
  }

  const getStateStyle = (status: string) => {
    if(status == '2'){
      return {
        'color': 'forestgreen',
        'backgroundColor': '#dcfce7',
      }
    }else{
      return {
        'color': '#0066ff',
        'backgroundColor': '#dbeafe',
      }
    }
  }

  const getStateName = (status: string) => {
    if(status == '2'){
      return '已完成'
    }else{
      return '即将开始'
    }
  }

  return (
    <View className=''>
      <View className='list-container'>
        {trainList.map((card, index) => (
          <View className='card' key={index} onClick={() => gotoPage(card.id)}>
            <Image className='card-image' src={card.image} />
            <View className='card-title'>{card.title}</View>
            <View className='location'>
              <Image src={MapPin} className='avatar1' />{card.location}
            </View>
            <View className='persons'><Image src={Users} className='avatar1' />{card.participants}人</View>
            <View className='during-date'><Image src={Calendar} className='avatar1' />{card.startDate}~{card.endDate}</View>
            <View className='state-finish' style={getStateStyle(card.status)}>{getStateName(card.status)}</View>
          </View>
        ))}
      </View>
      <View className='page-bottom'></View>
    </View>
  )
}
